<template>
  <div class="account-container">
    <el-row :gutter="20">
      <!-- 左侧信息卡片 -->
      <el-col :span="8">
        <el-card class="info-card">
          <div class="merchant-info">
            <div class="avatar-container">
              <el-avatar :size="100" :src="merchantInfo.avatar" />
              <el-upload
                class="avatar-uploader"
                action="/api/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" link>更换头像</el-button>
              </el-upload>
            </div>
            <div class="merchant-name">{{ merchantInfo.name }}</div>
            <div class="merchant-type">{{ merchantInfo.type }}</div>
            <div class="merchant-status">
              <el-tag :type="merchantInfo.status === '已认证' ? 'success' : 'warning'">
                {{ merchantInfo.status }}
              </el-tag>
            </div>
            <div class="merchant-meta">
              <div class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>入驻时间：{{ merchantInfo.joinTime }}</span>
              </div>
              <div class="meta-item">
                <el-icon><Location /></el-icon>
                <span>店铺地址：{{ merchantInfo.address }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 账户安全 -->
        <el-card class="security-card">
          <template #header>
            <div class="card-header">
              <span>账户安全</span>
              <el-button type="primary" link @click="handleSecuritySettings">
                安全设置
              </el-button>
            </div>
          </template>
          <div class="security-list">
            <div class="security-item">
              <div class="item-info">
                <el-icon><Lock /></el-icon>
                <span>登录密码</span>
              </div>
              <el-button type="primary" link @click="handleChangePassword">
                修改
              </el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <el-icon><Phone /></el-icon>
                <span>手机绑定</span>
                <span class="item-value">{{ maskPhone(merchantInfo.phone) }}</span>
              </div>
              <el-button type="primary" link @click="handleChangePhone">
                修改
              </el-button>
            </div>
            <div class="security-item">
              <div class="item-info">
                <el-icon><Message /></el-icon>
                <span>邮箱绑定</span>
                <span class="item-value">{{ maskEmail(merchantInfo.email) }}</span>
              </div>
              <el-button type="primary" link @click="handleChangeEmail">
                修改
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧认证信息 -->
      <el-col :span="16">
        <el-card class="certification-card">
          <template #header>
            <div class="card-header">
              <span>资质认证</span>
              <div class="header-actions">
                <el-button
                  v-if="merchantInfo.status !== '已认证'"
                  type="primary"
                  @click="handleSubmitCertification"
                >
                  提交认证
                </el-button>
                <el-button
                  v-if="merchantInfo.status === '已认证'"
                  type="primary"
                  link
                  @click="handleViewCertification"
                >
                  查看认证信息
                </el-button>
              </div>
            </div>
          </template>

          <el-form
            ref="certificationForm"
            :model="certificationForm"
            :rules="certificationRules"
            label-width="120px"
            class="certification-form"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="店铺名称" prop="shopName">
                    <el-input v-model="certificationForm.shopName" placeholder="请输入店铺名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="店铺类型" prop="shopType">
                    <el-select v-model="certificationForm.shopType" style="width: 100%" placeholder="请选择店铺类型">
                      <el-option label="个人店铺" value="personal" />
                      <el-option label="企业店铺" value="enterprise" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="联系人" prop="contactName">
                    <el-input v-model="certificationForm.contactName" placeholder="请输入联系人姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="certificationForm.contactPhone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="店铺地址" prop="address">
                <el-cascader
                  v-model="certificationForm.region"
                  :options="regionOptions"
                  style="width: 100%"
                  placeholder="请选择所在地区"
                />
                <el-input
                  v-model="certificationForm.address"
                  class="mt-2"
                  placeholder="请输入详细地址"
                />
              </el-form-item>
            </div>

            <!-- 营业执照信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Document /></el-icon>
                <span>营业执照信息</span>
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="营业执照号" prop="licenseNo">
                    <el-input v-model="certificationForm.licenseNo" placeholder="请输入营业执照号" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="法定代表人" prop="legalPerson">
                    <el-input v-model="certificationForm.legalPerson" placeholder="请输入法定代表人姓名" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="成立日期" prop="establishDate">
                    <el-date-picker
                      v-model="certificationForm.establishDate"
                      type="date"
                      style="width: 100%"
                      placeholder="请选择成立日期"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="营业期限" prop="businessTerm">
                    <el-date-picker
                      v-model="certificationForm.businessTerm"
                      type="daterange"
                      style="width: 100%"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="经营范围" prop="businessScope">
                <el-input
                  v-model="certificationForm.businessScope"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入经营范围"
                />
              </el-form-item>
            </div>

            <!-- 证件上传 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Upload /></el-icon>
                <span>证件上传</span>
              </div>
              <div class="upload-tips">
                <el-alert
                  title="请上传清晰的证件照片，支持jpg、png格式，单个文件不超过5MB"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </div>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="营业执照" prop="licenseImage">
                    <el-upload
                      class="certification-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'licenseImage')"
                      :before-upload="beforeUpload"
                      :headers="uploadHeaders"
                    >
                      <div class="upload-content">
                        <img
                          v-if="certificationForm.licenseImage"
                          :src="certificationForm.licenseImage"
                          class="uploaded-image"
                        />
                        <template v-else>
                          <el-icon class="uploader-icon"><Plus /></el-icon>
                          <div class="upload-tip">点击上传营业执照</div>
                          <div class="upload-desc">支持jpg、png格式，不超过5MB</div>
                        </template>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="法人身份证" prop="idCardImage">
                    <el-upload
                      class="certification-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'idCardImage')"
                      :before-upload="beforeUpload"
                      :headers="uploadHeaders"
                    >
                      <div class="upload-content">
                        <img
                          v-if="certificationForm.idCardImage"
                          :src="certificationForm.idCardImage"
                          class="uploaded-image"
                        />
                        <template v-else>
                          <el-icon class="uploader-icon"><Plus /></el-icon>
                          <div class="upload-tip">点击上传法人身份证</div>
                          <div class="upload-desc">支持jpg、png格式，不超过5MB</div>
                        </template>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="其他资质" prop="otherCertificates">
                    <el-upload
                      class="certification-uploader"
                      action="/api/upload"
                      :show-file-list="false"
                      :on-success="(res) => handleUploadSuccess(res, 'otherCertificates')"
                      :before-upload="beforeUpload"
                      :headers="uploadHeaders"
                    >
                      <div class="upload-content">
                        <img
                          v-if="certificationForm.otherCertificates"
                          :src="certificationForm.otherCertificates"
                          class="uploaded-image"
                        />
                        <template v-else>
                          <el-icon class="uploader-icon"><Plus /></el-icon>
                          <div class="upload-tip">点击上传其他资质证明</div>
                          <div class="upload-desc">支持jpg、png格式，不超过5MB</div>
                        </template>
                      </div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 认证状态 -->
            <div v-if="merchantInfo.status === '已认证'" class="certification-status">
              <el-result
                icon="success"
                title="认证成功"
                :sub-title="merchantInfo.certificationTime"
              >
                <template #extra>
                  <el-button type="primary" @click="handleViewCertification">
                    查看认证信息
                  </el-button>
                </template>
              </el-result>
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpdatePassword">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Calendar,
  Location,
  Lock,
  Phone,
  Message,
  Plus,
  User,
  Document,
  Upload
} from '@element-plus/icons-vue'
import {
  getMerchantInfo,
  updateMerchantInfo,
  updatePassword,
  submitCertification
} from '@/api/merchant'

// 商家信息
const merchantInfo = reactive({
  avatar: '',
  name: '',
  type: '',
  status: '',
  joinTime: '',
  address: '',
  phone: '',
  email: '',
  certificationTime: ''
})

// 认证表单
const certificationForm = reactive({
  shopName: '',
  shopType: '',
  contactName: '',
  contactPhone: '',
  region: [],
  address: '',
  licenseNo: '',
  legalPerson: '',
  establishDate: '',
  businessTerm: [],
  businessScope: '',
  licenseImage: '',
  idCardImage: '',
  otherCertificates: ''
})

// 表单验证规则
const certificationRules = {
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  shopType: [
    { required: true, message: '请选择店铺类型', trigger: 'change' }
  ],
  contactName: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  licenseNo: [
    { required: true, message: '请输入营业执照号', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法定代表人', trigger: 'blur' }
  ],
  establishDate: [
    { required: true, message: '请选择成立日期', trigger: 'change' }
  ],
  businessTerm: [
    { required: true, message: '请选择营业期限', trigger: 'change' }
  ],
  businessScope: [
    { required: true, message: '请输入经营范围', trigger: 'blur' }
  ],
  licenseImage: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  idCardImage: [
    { required: true, message: '请上传法人身份证', trigger: 'change' }
  ]
}

// 密码修改
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取商家信息
const fetchMerchantInfo = async () => {
  try {
    const { data } = await getMerchantInfo()
    Object.assign(merchantInfo, data)
    if (data.certification) {
      Object.assign(certificationForm, data.certification)
    }
  } catch (error) {
    console.error('获取商家信息失败:', error)
    ElMessage.error('获取商家信息失败')
  }
}

// 头像上传
const handleAvatarSuccess = (res) => {
  merchantInfo.avatar = res.url
  updateMerchantInfo({ avatar: res.url })
}

const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 证件上传
const handleUploadSuccess = (res, field) => {
  certificationForm[field] = res.url
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片格式!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
  }
  return isImage && isLt5M
}

// 提交认证
const handleSubmitCertification = async () => {
  try {
    await submitCertification(certificationForm)
    ElMessage.success('提交成功，请等待审核')
    fetchMerchantInfo()
  } catch (error) {
    console.error('提交认证失败:', error)
    ElMessage.error('提交认证失败')
  }
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    await updatePassword(passwordForm)
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改密码失败:', error)
      ElMessage.error('修改密码失败')
    }
  }
}

// 手机号脱敏
const maskPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ''
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return ''
  const [name, domain] = email.split('@')
  return `${name.charAt(0)}***@${domain}`
}

// 上传相关
const uploadHeaders = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

// 初始化
onMounted(() => {
  fetchMerchantInfo()
})
</script>

<style scoped>
.account-container {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
  
  .merchant-info {
    text-align: center;
    
    .avatar-container {
      margin-bottom: 16px;
      
      .avatar-uploader {
        margin-top: 8px;
      }
    }
    
    .merchant-name {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }
    
    .merchant-type {
      font-size: 14px;
      color: #606266;
      margin-bottom: 8px;
    }
    
    .merchant-status {
      margin-bottom: 16px;
    }
    
    .merchant-meta {
      .meta-item {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        margin-bottom: 8px;
        color: #606266;
        
        .el-icon {
          font-size: 16px;
        }
      }
    }
  }
}

.security-card {
  .security-list {
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #ebeef5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-info {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          font-size: 18px;
          color: #909399;
        }
        
        .item-value {
          color: #909399;
          margin-left: 8px;
        }
      }
    }
  }
}

.certification-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .certification-form {
    .form-section {
      margin-bottom: 32px;
      
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 20px;
        padding-left: 12px;
        border-left: 4px solid #409eff;
        
        .el-icon {
          font-size: 18px;
        }
      }
    }
  }
  
  .upload-tips {
    margin-bottom: 20px;
  }
  
  .certification-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 200px;
    
    &:hover {
      border-color: #409eff;
    }
    
    .upload-content {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      
      .uploader-icon {
        font-size: 28px;
        color: #8c939d;
        margin-bottom: 8px;
      }
      
      .upload-tip {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .upload-desc {
        font-size: 12px;
        color: #909399;
      }
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
  
  .certification-status {
    margin-top: 32px;
    padding: 32px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.mt-2 {
  margin-top: 8px;
}

/* 响应式布局优化 */
@media screen and (max-width: 1200px) {
  .el-col-8 {
    width: 100%;
  }
  
  .el-col-16 {
    width: 100%;
  }
  
  .el-col-12 {
    width: 100%;
  }
}
</style>